<template>
    <div>
        <div style="margin: 10px 0">
            <span>姓 名</span>
            <el-input class="search-box" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="realName"></el-input>
            <span>证件号</span>
            <el-input class="search-box" placeholder="身份证号" suffix-icon="el-icon-search" v-model="idcard"></el-input>
            <!--      <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-message" class="ml-5" v-model="email"></el-input>-->
            <!--      <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-position" class="ml-5" v-model="address"></el-input>-->
            <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
        </div>

        <div style="margin: 10px 0">
            <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
            <!--            <el-popconfirm-->
            <!--                    class="ml-5"-->
            <!--                    confirm-button-text='确定'-->
            <!--                    cancel-button-text='我再想想'-->
            <!--                    icon="el-icon-info"-->
            <!--                    icon-color="red"-->
            <!--                    title="您确定批量删除这些数据吗？"-->
            <!--                    @confirm="delBatch">-->
            <!--                <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>-->
            <!--            </el-popconfirm>-->
            <!--            &lt;!&ndash; <el-upload action="http://localhost:9090/athlete/import" :show-file-list="false" accept="xlsx" :on-success="handleExcelImportSuccess" style="display: inline-block">-->
            <!--              <el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>-->
            <!--            </el-upload>-->
            <!--            <el-button type="primary" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button> &ndash;&gt;-->
        </div>

        <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <!--<el-table-column prop="id" label="ID" width="80" sortable></el-table-column>-->
            <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
            <el-table-column label="姓名" align="center">
                <template slot-scope="scope">
                    <div style="display: inline-block">
                        <el-image style="width: 60px; border-radius: 50%;
                        position: relative;height: 60px" :src="scope.row.avatar"
                                  :preview-src-list="[scope.row.avatar]"></el-image>
                        <!--                        <el-table-column prop="realName" label="姓名" align="center"></el-table-column>-->
                        <span style="position:relative; bottom:13px;margin-left: 14px">{{ scope.row.realName }}</span>
                    </div>

                </template>
            </el-table-column>
            <el-table-column slot-scop="scope" prop="sex" label="性别" :formatter="sexFormatter"
                             align="center"></el-table-column>
            <el-table-column prop="idcard" label="身份证号" align="center"></el-table-column>
            <!--            <el-table-column prop="organization" label="所属单位" align="center"></el-table-column>-->
            <!--            <el-table-column prop="rank" label="排名" align="center"></el-table-column>-->
            <!--            <el-table-column prop="rankStatus" label="" align="center"></el-table-column>-->
            <!--            <el-table-column prop="realName" label="姓名" align="center"></el-table-column>-->
            <!--            <el-table-column prop="scoreLevel" label="计入级别" align="center"></el-table-column>-->
            <!--            <el-table-column prop="total" label="总分" align="center"></el-table-column>-->
            <!--            <el-table-column prop="userId" label="用户id" align="center"></el-table-column>-->
            <el-table-column prop="wtId" label="wtid" align="center"></el-table-column>
            <!--            <el-table-column prop="year" label="所属年份" align="center"></el-table-column>-->
            <!--            <el-table-column prop="diffRankVal" label="" align="center"></el-table-column>-->

            <el-table-column label="操作" width="220" align="center">
                <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
                        <el-button type="text" @click="handleEdit(scope.row)"><i class="el-icon el-icon-edit"></i></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                        <el-popconfirm
                                class="ml-5"
                                confirm-button-text='确定'
                                cancel-button-text='我再想想'
                                icon="el-icon-info"
                                icon-color="red"
                                title="您确定删除吗？"
                                @confirm="del(scope.row.idcard)"
                        >
                            <el-button type="text" slot="reference"><i class="el-icon el-icon-delete"/></el-button>
                        </el-popconfirm>
                    </el-tooltip>

                </template>
            </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[10, 30, 50, 100]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog title="编辑信息" :visible.sync="dialogFormVisible"
                   width="40%" :close-on-click-modal="false" ref="updateInsertDialog">
            <el-form class="TKform" label-width="120px" :model="ruleForm" :rules="rules" ref="athleteForm"
                     size="small" style="width: 80%; margin: 0 auto" label-position="left">
                <el-form-item prop="avatar" label="头    像:">
                    <imgUpload :transfer="getmsg" :imgUrl="imgUrl"></imgUpload>
                </el-form-item>

                <el-form-item prop="realName" label="姓    名:">
                    <el-input v-model="ruleForm.realName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="sex" label="性    别:">
                    <el-select v-model="ruleForm.sex" placeholder="请选择性别" @change="sexChange" style="width:100%">
                        <el-option v-for="item in sex"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="idcard" label="身份证:">
                    <el-input v-model="ruleForm.idcard" autocomplete="off" id="idcardEnabled"></el-input>
                </el-form-item>
                <el-form-item prop="wtId" label="wtId:">
                    <el-input v-model="ruleForm.wtId" autocomplete="off"></el-input>
                </el-form-item>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import imgUpload from '../components/imgUpload.vue'
    import router from "../router";

    export default {
        name: "Athlete",
        data() {
            return {
                tableData: [],
                total: 0,
                pageNum: 1,
                pageSize: 10,
                realName: "",
                idcard: "",
                form: {},
                dialogFormVisible: false,
                multipleSelection: [],
                user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
                sex: [
                    {value: '1', label: '男'},
                    {value: '2', label: '女'},
                ],
                imgUrl: '',
                ruleForm: {
                    realName: '',
                    sex: '',
                    idcard: '',
                    wtId: '',
                    avatar: ''
                },
                rules: {
                    realName: [
                        {required: true, message: '请输入姓名', trigger: 'blur'},
                    ],
                    sex: [
                        {required: true, message: '请选择性别', trigger: 'change'}
                    ],
                    idcard: [
                        {required: true, message: '请输入身份证号', trigger: 'blur',readonly:true},
                        {
                            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '你的身份证格式不正确'
                        }
                    ]
                }
            }
        },
        created() {
            this.load()
        },
        mounted() {
            this.dialogFormVisible = true
            this.$refs.updateInsertDialog.rendered = true //updateInsertDialog是dialog的ref;
            this.dialogFormVisible = false
        },
        components: {imgUpload},
        methods: {
            load() {
                const data = {
                    "page": this.pageNum,
                    "pageSize": this.pageSize,
                    "realName": this.realName,
                    "idcard": this.idcard
                }
                this.request.post("/athlete/page", data).then(res => {
                    //this.tableData = res.data.records
                    this.tableData = res.data.data
                    this.total = res.data.total

                })
            },
            sexFormatter(row) {
                if (row.sex === "1") {
                    return "男"
                } else if (row.sex === "2") {
                    return "女"
                }
            },
            getmsg(img) {
                this.imgUrl = ''
                this.imgData = img

            },
            sexChange(){
                // //强制刷新
                this.$forceUpdate()
            },
            save() {
                var that = this
                this.$refs['athleteForm'].validate((valid) => {
                    if (valid) {
                        let formData = new FormData();
                        if (this.imgData == null && this.imgUrl == '') {
                            that.$message.error("请先上传证件照")
                            return
                        }
                        if (this.imgData && this.imgUrl == '') {
                            formData.append('file', this.imgData, this.ruleForm.idcard + '.png');
                             that.request.post("/file/upload", formData).then(async res => {
                                if (res.code == 200) {
                                    this.ruleForm.avatar = res.data.imgUrl
                                    // this.imgUrl = res.data.imgUrl
                                    await that.request.post("/athlete/save", this.ruleForm).then( res => {
                                        if (res.code === 200) {
                                            this.$message.success(res.message)
                                            this.dialogFormVisible = false
                                            location.reload()
                                        } else {
                                            this.$message.error(res.message)
                                        }
                                    })
                                } else {
                                    that.$message.error("头像更新失败")
                                }
                            })
                        } else {
                            this.ruleForm.avatar = this.imgUrl
                            that.request.post("/athlete/save", this.ruleForm).then( res => {
                                if (res.code === 200) {
                                    this.$message.success(res.message)
                                    this.dialogFormVisible = false
                                    location.reload()
                                } else {
                                    this.$message.error(res.message)
                                }
                            })
                        }

                    }
                })

            },
            handleAdd() {
                this.dialogFormVisible = true
                this.ruleForm.realName = ''
                this.$set(this.ruleForm, 'sex', '')
                this.ruleForm.idcard = ''
                this.ruleForm.avatar = ''
                this.ruleForm.wtId = ''
                this.imgUrl = ''
                this.imgData = null
                document.getElementById("idcardEnabled").removeAttribute('readonly')
            },
            handleEdit(row) {
                console.log(row.avatar)
                this.ruleForm.realName = row.realName
                this.$set(this.ruleForm, 'sex', row.sex)
                this.ruleForm.idcard = row.idcard
                this.ruleForm.avatar = row.avatar
                this.ruleForm.wtId = row.wtId
                this.imgUrl = row.avatar
                this.dialogFormVisible = true
                // let fileName = row.idcard+'.png'
                // this.imgData = new File([fileName],row.avatar)
                document.getElementById("idcardEnabled").setAttribute('readonly','true')
            },
            del(idcard) {
                this.request.delete("/athlete/" + idcard).then(res => {
                    if (res.code === 200) {
                        this.$message.success("删除成功")
                        this.load()
                    } else {
                        this.$message.error("删除失败")
                    }
                })
            },
            handleSelectionChange(val) {
                console.log(val)
                this.multipleSelection = val
            },
            delBatch() {
                if (!this.multipleSelection.length) {
                    this.$message.error("请选择需要删除的数据")
                    return
                }
                let ids = this.multipleSelection.map(v => v.idcard)  // [{}, {}, {}] => [1,2,3]
                this.request.post("/athlete/del/batch", ids).then(res => {
                    if (res.code === 200) {
                        this.$message.success("批量删除成功")
                        this.load()
                    } else {
                        this.$message.error("批量删除失败")
                    }
                })
            },
            reset() {
                this.realName = ""
                this.idcard = ""
                this.load()
            },
            handleSizeChange(pageSize) {
                console.log(pageSize)
                this.pageSize = pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {
                console.log(pageNum)
                this.pageNum = pageNum
                this.load()
            },
            handleFileUploadSuccess(res) {
                this.form.file = res
            },
            handleImgUploadSuccess(res) {
                this.form.img = res
            },
            download(url) {
                window.open(url)
            },
            exp() {
                window.open("http://localhost:9090/athlete/export")
            },
            handleExcelImportSuccess() {
                this.$message.success("导入成功")
                this.load()
            }
        }
    }
</script>


<style>
    .headerBg {
        background: #eee !important;
    }

    .search-box {
        width: 200px;
        margin: 0 10px 0 10px;
    }
    .el-button {
        margin: 0px 6px 12px;
    }
    .el-icon {
        font-size: 16px;
    }
</style>
